import { ImportOutlined, PlusOutlined, TagOutlined, DeleteOutlined, ExportOutlined } from '@ant-design/icons';
import { Button, Divider, Tabs, message, Radio } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { history } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryVip, batchRemoveVip, exportMemberAndCard } from './service';
import { HasPermission } from '@/components/AuthComponent/HasPermission';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);
const { TabPane } = Tabs;

const OperType = {
  '16': [
    {
      text: '全部',
      value: '16',
    },
  ],
  '15': [
    {
      text: '全部',
      value: '15',
    },
    {
      text: '绑卡未开卡',
      value: '4',
    },
    {
      text: '已开卡',
      value: '5',
    },
    {
      text: '开卡已过期',
      value: '6',
    },
    {
      text: '最近未来上课',
      value: '7',
    },
    {
      text: '最近会员到期',
      value: '8',
    },
    {
      text: '最近生日',
      value: '9',
    }
  ],
  '14':[
    {
      text: '全部',
      value: '14',
    },
    {
      text: '未到店潜客',
      value: '1',
    },
    {
      text: '到店未体验潜客',
      value: '2',
    },
    {
      text: '体验课潜客',
      value: '3',
    }
  ]
}
/**
 * 跳转详情页
 * @param {*} record 
 */
const goToDetail = async record => {
  history.push(`/vip/center/detail/${record.id}`);
}

/**
 * 跳转编辑页
 * @param {*} record 
 */
const goToEdit = async record => {
  history.push(`/vip/center/update/${record.id}`);
}

/**
 * 跳转新增页
 * @param {*} record 
 */
const goToSave = async => {
  history.push(`/vip/center/save`);
}

/**
 * 跳转卡详情
 * @param {*} cardId 
 * @param {*} memberId 
 */
const go2CardDetail = (cardId, memberId) => {
  history.push(`/vip/card/detail/${cardId}/${memberId}`);
}

const List = props => {
  const actionRef = useRef();
  const [formValues, setFormValues] = useState({});
  const [tabActiveKey, setTabActiveKey] = useState('16');
  const [tabChildActiveKey, setTabChildActiveKey] = useState('16');
  const [tabChildActiveList, setTabChildActiveList] = useState([{
    text: '全部',
    value: 16,
  }]);
  const [isSearch, setIsSearch] = useState(true);
  const [days, setDays] = useState("7");
  useEffect(() => {
    let type = props.location.query.type
    if (type) {
      setIsSearch(false)
      setTabActiveKey('15')
      setTabChildActiveList(OperType['15'])
      setDays("7")
      if (type == '1') {
        setTabChildActiveKey("7")
      } else if (type == '2') {
        setTabChildActiveKey("8")
      } else if (type == '3') {
        setTabChildActiveKey("9")
      }
    }
  }, []);
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '会员状态',
      dataIndex: 'status',
      valueEnum: {
        '0': {
          text: '草稿',
          status: 'Warning',
        },
        '1': {
          text: '未到店潜客',
          status: 'Processing',
        },
        '2': {
          text: '到店未体验潜客',
          status: 'Processing',
        },
        '3': {
          text: '体验课潜客',
          status: 'Success',
        },
        '4': {
          text: '绑卡未开卡会员',
          status: 'Success',
        },
        '5': {
          text: '已开卡会员',
          status: 'Success',
        },
        '6': {
          text: '开卡过期会员',
          status: 'Error',
        }
      }
    },
    {
      title: '电话',
      dataIndex: 'phone'
    },
    {
      title: '会员卡',
      dataIndex: 'cardGroupByMemberDTOList',
      hideInSearch: true,
      render: (text, record) => {
        if (Array.isArray(record.cardGroupByMemberDTOList) && record.cardGroupByMemberDTOList.length > 0) {
          return record.cardGroupByMemberDTOList.map((item) => <><a onClick={() => go2CardDetail(item.cardId, record.id)} key={item.cardId}>{item.cardName}</a><br /></>)
        }
      }
    },
    {
      title: '销售',
      dataIndex: 'salesName',
    },
    {
      title: '教练',
      dataIndex: 'coachName',
    },
    {
      title: '来源',
      dataIndex: 'source',
      valueEnum: {
        1: {
          text: '老客开发',
          status: 'Success',
        },
        2: {
          text: '会员推荐',
          status: 'Success',
        },
        3: {
          text: '大众',
          status: 'Success',
        },
        4: {
          text: '进店',
          status: 'Success',
        },
        5: {
          text: '微信',
          status: 'Success',
        },
        6: {
          text: '发单',
          status: 'Success',
        },
        7: {
          text: '活动',
          status: 'Success',
        },
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <AuthButton auth={[`vip:detail`]} type="link" onClick={() => goToDetail(record)}>详情</AuthButton>
          <AuthDivider auth={['vip:detail', `vip:update`]} type="vertical"></AuthDivider>
          <AuthButton auth={[`vip:update`]} type="link" onClick={() => goToEdit(record)}>编辑</AuthButton>
        </>
      ),
    },
  ];

  /**
 *  删除节点
 * @param selectedRows
 */

  const handleRemove = async selectedRows => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      let result = await batchRemoveVip({
        ids: selectedRows.map(row => row.id),
      });
      hide();
      if (result.code == 0) {
        message.success('删除成功，即将刷新');
        actionRef.current.reload();
        return true;
      } else {
        message.error(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  /**
   * 导出
   */
  const goToExport = async () => {
    const hide = message.loading('正在导出');
    try {
      await exportMemberAndCard({ ...formValues });
      hide();
      message.success('导出成功，即将刷新');
      return true;
    } catch (error) {
      hide();
      message.error('导出失败，请重试');
      return false;
    }
  }
  /**
   * 
   * @param {*} tabActiveKey 
   */
  const onTabChange = tabActiveKey => {
    setTabActiveKey(tabActiveKey)
    setTabChildActiveKey(OperType[tabActiveKey]?.[0].value);
    setTabChildActiveList(OperType[tabActiveKey])
    if(tabActiveKey === '16'){
      setIsSearch(true);
    }else{
      setIsSearch(false);
    }
    actionRef?.current?.reload();
  }
  const daysChange = (e) => {
    setDays(e.target.value)
    actionRef.current.reload();
  }

  return (
    <PageHeaderWrapper tabActiveKey={tabActiveKey}
      onTabChange={onTabChange}
      tabList={[
        {
          key: '16',
          tab: '全部会员',
        },
        {
          key: '15',
          tab: '会员',
        },
        {
          key: '14',
          tab: '潜客',
        },
      ]}>
      <Tabs tabPosition={'left'} activeKey={tabChildActiveKey} onChange={(activeKey)=>setTabChildActiveKey(activeKey)} style={{background:'#ffffff'}}>
        {tabChildActiveList?.map(i => (
          <TabPane tab={`${i.text}`} key={i.value}>
            <ProTable
              actionRef={actionRef}
              rowKey="id"
              search={isSearch}
              toolBarRender={(action, { selectedRows }) => [
                tabActiveKey == '16' && <AuthButton auth={[`vip:add`]} type="primary" icon={<PlusOutlined />} onClick={() => goToSave()}>新增</AuthButton>,
                // <AuthButton auth={[`vip:batch:import`]} type="primary" icon={<ImportOutlined />}  onClick={() => goToImport()}>批量导入</AuthButton>,
                tabActiveKey == '16' && <AuthButton auth={[`vip:batch:export`]} icon={<ExportOutlined />} onClick={() => goToExport()}>全量导出</AuthButton>,
                tabActiveKey == '16' && <AuthButton auth={[`vip:batch:delete`]} icon={<DeleteOutlined />} danger onClick={() => handleRemove(selectedRows)}> 批量删除 </AuthButton>,
                ((tabChildActiveKey == '7' || tabChildActiveKey == '8' || tabChildActiveKey == '9')  && tabActiveKey ==='15') && <Radio.Group value={days} buttonStyle="solid" onChange={daysChange}>
                  <Radio.Button value="7">7天</Radio.Button>
                  <Radio.Button value="14">14天</Radio.Button>
                  <Radio.Button value="30">30天</Radio.Button>
                  <Radio.Button value="60">60天</Radio.Button>
                </Radio.Group>
              ]}
              tableAlertRender={({ selectedRowKeys, selectedRows }) => (
                <div>
                  已选择{' '}
                  <a
                    style={{
                      fontWeight: 600,
                    }}
                  >
                    {selectedRowKeys.length}
                  </a>{' '}
                  项
                </div>
              )}
              request={params => {
                let _params = {
                  pageNum: params.current,
                  ...params,
                }
                delete _params.current
                setFormValues(params)
                _params.operType = tabChildActiveKey
                if ((tabChildActiveKey == '7' || tabChildActiveKey == '8' || tabChildActiveKey == '9') && tabActiveKey === '15') {
                  _params.days = days
                }
                return queryVip(_params)
              }}
              postData={result => result.list}
              columns={columns}
              rowSelection={{}}
            />
          </TabPane>
        ))}
      </Tabs>

    </PageHeaderWrapper>
  );
};

export default List;
